import React, { useRef, useState, useEffect } from 'react';
import {
  Form,
  Input,
  Select,
  Row,
  Col,
  Card,
  Space,
  Button,
  message,
  Spin,
} from 'antd';
// @ts-ignore
import Reset from './ResetPassword.js';
import { hehLocalStorage, encryption } from '@/utils/utils';
import { adminRuleTypeArray } from '@/utils/constant';
import { apiUserUpdate, resetPassword } from '@/services/otherServices';
import { userInfo } from '@/services/loginServices';
import { useRequest } from '@umijs/hooks';
import { connect } from 'dva';

const FormItem = Form.Item;
const Detail = (props: any) => {
  const { dispatch } = props;
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
      md: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 18 },
      md: { span: 18 },
    },
  };

  const { loading: userInfoLoading, run: getUserInfo } = useRequest(userInfo, {
    manual: true,
    debounceInterval: 500,
    onSuccess: (res, params) => {
      if (res.locked !== undefined) {
        res.locked = res.locked === true ? 2 : 1;
      }
      form.setFieldsValue(res);
    },
  });

  /*
   * 编辑请求
   * */
  const { loading, run } = useRequest(apiUserUpdate, {
    manual: true,
    debounceInterval: 500,
    onSuccess: (res, params) => {
      const value = form.getFieldsValue();
      const userInfo = hehLocalStorage.getItem('loginUserInfo');
      if (value.locked !== undefined) {
        value.locked = value.locked !== 1;
      }
      if (value.username !== undefined) {
        value['userName'] = value.username;
        delete value['username'];
      }
      dispatch({
        type: 'globalModel/setUserInfo',
        payload: {
          ...userInfo,
          ...value,
          username: value.userName,
        },
      });

      hehLocalStorage.setItem('loginUserInfo', {
        ...userInfo,
        ...value,
        username: value.userName,
      });
      message.success('更新成功');
    },
  });

  useEffect(() => {
    getUserInfo({});
  }, []);

  const onFinish = (values: { [key: string]: any }) => {
    const userInfo = hehLocalStorage.getItem('loginUserInfo');
    if (userInfo?.userId) {
      if (values.username !== undefined) {
        values['userName'] = values.username;
        delete values['username'];
      }

      run({
        id: userInfo.userId,
        ...values,
      });
    }
  };

  const onFinishFailed = (errorInfo: any) => {};

  const onValuesChange = (changedValues: { [key: string]: any }) => {};
  return (
    <Card title={'个人用户信息'}>
      <Reset
        visible={visible}
        onCancel={() => setVisible(false)}
        callBack={(data: any) => {
          if (data.confirm) {
            delete data.confirm;
          }
          resetPassword({
            password: encryption.MD5(data.password),
            passwordNew: encryption.MD5(data.passwordNew),
          }).then((res: any) => {
            if (res?.success) {
              message.success('修改成功');
              setVisible(false);
            } else {
              message.error(res.message);
            }
          });
        }}
      />
      <Spin spinning={userInfoLoading}>
        <Form
          hideRequiredMark
          style={{ marginTop: 8 }}
          form={form}
          name="basic"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          onValuesChange={onValuesChange}
        >
          <Row gutter={12}>
            <Col span={12} offset={6}>
              <FormItem {...formItemLayout} label={'账号'} name="loginCode">
                <Input disabled={true} />
              </FormItem>
            </Col>
            <Col span={12} offset={6}>
              <FormItem
                rules={[{ required: true, message: '请输入昵称' }]}
                {...formItemLayout}
                label={'昵称'}
                name="username"
              >
                <Input />
              </FormItem>
            </Col>
            <Col span={12} offset={6}>
              <FormItem
                rules={[
                  { required: true, message: '请输入手机号' },
                  {
                    pattern: /^[0-9\(\)\-\+]{11,}$/,
                    message: '请输入正确的联系方式',
                  },
                ]}
                {...formItemLayout}
                label={'手机号'}
                name="telephone"
              >
                <Input />
              </FormItem>
            </Col>
            <Col span={12} offset={6}>
              <FormItem {...formItemLayout} label={'角色'} name="userType">
                <Select disabled={true}>
                  {adminRuleTypeArray.map(item => (
                    <Select.Option key={item.value} value={item.value}>
                      {item.label}
                    </Select.Option>
                  ))}
                </Select>
              </FormItem>
            </Col>
            <Col span={12} offset={6}>
              <FormItem {...formItemLayout} label={'状态'} name="locked">
                <Select disabled={true}>
                  <Select.Option value={1}>正常</Select.Option>
                  <Select.Option value={2}>锁定</Select.Option>
                </Select>
              </FormItem>
            </Col>
            <Col span={24} style={{ textAlign: 'center' }}>
              <Form.Item style={{ margin: 0 }}>
                <Space>
                  <Button loading={loading} type="primary" htmlType="submit">
                    修改个人信息
                  </Button>
                  <Button type="primary" onClick={() => setVisible(true)}>
                    修改密码
                  </Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Spin>
    </Card>
  );
};
export default connect(({ globalModel }: any) => ({
  btnPermissionLoading: globalModel.btnPermissionLoading,
}))(Detail);
